/**
 * @(#)FileAjaxController.java, 2018/2/7.
 * <p/>
 * Copyright 2018 Kerr Wang, Inc. All rights reserved.
 * KERRWANG PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package org.wangzx.exercise.controller.xhr;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.wangzx.exercise.meta.vo.common.AjaxResult;
import org.wangzx.exercise.meta.vo.common.ResponseCode;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.UUID;

/**
 * @author hzwangzuxiang(ahscwzx@163.com)
 */
@Controller
@RequestMapping("/file")
public class FileAjaxController extends BaseAjaxController {
    static private final Logger logger = LoggerFactory.getLogger(FileAjaxController.class);

    @RequestMapping("/api/upload")
    @ResponseBody
    public AjaxResult fileUpload(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession(false);
        //未登陆或者不是卖家不能上传图片
        if(session == null || (Integer)session.getAttribute("userType") != 2) {
            return initFailureResult(ResponseCode.UNAUTHORIZED);
        }
        String pathRoot = session.getServletContext().getRealPath("");

        logger.info("[op:fileUpload] file upload");

        if (!file.isEmpty()) {
            //生成uuid作为文件名称  
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //获得文件类型
            String contentType = file.getContentType();
            //获得文件后缀名
            String imageSuffix = contentType.substring(contentType.indexOf("/") + 1);
            String path = "/img/" + uuid + "." + imageSuffix;
            try {
                file.transferTo(new File(pathRoot + path));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return initSuccessResult(path);
        }
        return initFailureResult(ResponseCode.FAIL);
    }
}
